import axios, {AxiosRequestConfig} from 'axios';
import {errHandler, requestInterceptor, responseInterceptor} from './interceptors';

// 创建axios
const service = axios.create({
  timeout: 100000, // 请求超时时间
});
// request拦截器
service.interceptors.request.use(requestInterceptor, errHandler);

// respone拦截器
service.interceptors.response.use(responseInterceptor, errHandler);

const http = {
  /**
   * post方法，对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @returns Promise
   */
  post(url: string, params?: any) {
    return new Promise((resolve, reject) => {
      service({
        url,
        method: 'post',
        data: params,
      } as AxiosRequestConfig)
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  /**
   * get方法，对应get请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @returns Promise
   */
  get(url: string, param?: any) {
    return new Promise((resolve, reject) => {
      service({
        url,
        method: 'get',
        params: param,
        Headers: {
          'content-type': 'application/json;charset=UTF-8',
        },
      } as AxiosRequestConfig)
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};
export default http;
